package cn.hinglo.permission.controller;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author HingLo
 * @createTime: 2020/3/19 21:53
 * @description:
 */
public class WsClient extends WebSocketClient {

    public WsClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake arg0) {
        System.out.println("握手成功");

    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        System.out.println("连接关闭");
    }

    @Override
    public void onError(Exception arg0) {
        System.out.println("发生错误");
    }

    @Override
    public void onMessage(String arg0) {
        System.out.println("收到消息" + arg0);
    }

    public static void main(String[] args) throws URISyntaxException, InterruptedException {
        WsClient wsClient = new WsClient(new URI("ws://127.0.0.1:8888"));
        wsClient.connect();
        // 判断是否连接成功，未成功后面发送消息时会报错
        while (!wsClient.getReadyState().equals(ReadyState.OPEN)) {
            System.out.println("连接中···请稍后");
            Thread.sleep(1000);
        }

       String userCmd = "{cmd:5}";
        wsClient.send(userCmd);
        System.out.println("发送成功");

    }
}
